package tests;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.management.RuntimeErrorException;

public class LoggerTool {
	private static String loggerFilePath="";

	private static String readFile(String pathFile) throws IOException{
		String everything="";
		BufferedReader br = new BufferedReader(new FileReader(pathFile));
		try {
			StringBuilder sb = new StringBuilder();
			String line = br.readLine();

			while (line != null) {
				sb.append(line);
				sb.append(System.lineSeparator());
				line = br.readLine();
			}
			everything = sb.toString();
		} finally {
			br.close();
		}
		return everything;
	}
	private static String getLoggerFile() throws IOException{
		if (loggerFilePath==""){
			String Conf = LoggerTool.readFile(".\\src\\resources\\log4j.properties");
			String logPath = null;
			try {
				Pattern regex = Pattern.compile("log\\s*=\\s*(.*)");
				Matcher regexMatcher = regex.matcher(Conf);
				if (regexMatcher.find()) {
					logPath = regexMatcher.group(1);
				} 
			} catch (PatternSyntaxException ex) {
				// Syntax error in the regular expression
			}

			String LogName = null;
			if(logPath!=null){			
				try {
					Pattern regex = Pattern.compile("log4j\\.appender\\.FILE\\.File=.*?/(.*)");
					Matcher regexMatcher = regex.matcher(Conf);
					if (regexMatcher.find()) {
						LogName = regexMatcher.group(1);
					} 
				} catch (PatternSyntaxException ex) {
					// Syntax error in the regular expression
				}

			}
			if(logPath!=null && (LogName!=null)){
				String logpathfile = logPath+"\\"+LogName;
				loggerFilePath = logpathfile.replaceAll("\\\\\\\\+", "\\\\");
				int i=0;
				i++;
			}
			else {
				throw new RuntimeErrorException(null, "LogNotFound");
			}
		}
		return LoggerTool.readFile(loggerFilePath);
	}
	
	
	public static boolean isInLog(Pattern regex){
		String data="";
		try {
			data = LoggerTool.getLoggerFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		boolean foundMatch = false;
		try {
			Matcher regexMatcher = regex.matcher(data);
			foundMatch = regexMatcher.find();
		} catch (PatternSyntaxException ex) {
			// Syntax error in the regular expression
		}
		return foundMatch;
	}

}
